package com.starlink.databaseservice.service;

import com.starlink.databaseservice.model.Post;
import com.starlink.databaseservice.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class PostService {
    @Autowired
    private PostRepository postRepository;

    public Page<Post> getList(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size);

        Page<Post> all = postRepository.findAll(pageable);

        return all;
    }

    public Post getPostRandom() {
        return postRepository.findRandom();
    }

    public void updateLabel(Long id, Short label) {
        Optional<Post> byId = postRepository.findById(id);
        if (byId.isPresent()) {
            Post post = byId.get();
            post.setLabel(label);
            postRepository.save(post);
        }
    }

}
